import { promises as fs } from 'fs'
import { join, extname } from 'path'

interface AnalyzeResult {
  totalFiles: number
  fileTypes: Record<string, number>
  typeSafeFiles: {
    total: number
    byType: Record<string, number>
    percentage: number
  }
  jstsFiles: {
    total: number
    typeSafe: number
    regular: number
    typeSafePercentage: number
  }
}

export default defineEventHandler(async (event) => {
  try {
    const body = await readBody(event)
    const { directory } = body

    if (!directory || typeof directory !== 'string') {
      throw createError({
        statusCode: 400,
        statusMessage: '请提供有效的目录路径'
      })
    }

    const result = await analyzeDirectory(directory)
    return result
  } catch (error: any) {
    throw createError({
      statusCode: 500,
      statusMessage: error.message || '分析目录时出错'
    })
  }
})

async function analyzeDirectory(directoryPath: string): Promise<AnalyzeResult> {
  const fileTypes: Record<string, number> = {}
  const typeSafeFiles: Record<string, number> = {}
  let totalFiles = 0
  let totalTypeSafeFiles = 0
  let totalJsTs = 0
  let typeSafeJsTs = 0

  async function isTypeSafeFile(filePath: string): Promise<boolean> {
    try {
      // 只检查 .ts, .js, .tsx, .jsx 文件
      const ext = extname(filePath).toLowerCase()
      if (!['.ts', '.tsx', '.js', '.jsx'].includes(ext)) {
        return false
      }

      // 读取文件前几行查找 @ts-check 注释
      const content = await fs.readFile(filePath, 'utf-8')
      const lines = content.split('\n').slice(0, 10) // 只检查前10行
      
      return lines.some(line => 
        line.trim().includes('// @ts-check') || 
        line.trim().includes('//@ts-check')
      )
    } catch (error) {
      // 如果读取文件失败，返回 false
      return false
    }
  }

  async function scanDirectory(currentPath: string) {
    try {
      const items = await fs.readdir(currentPath, { withFileTypes: true })
      
      for (const item of items) {
        const itemPath = join(currentPath, item.name)
        
        if (item.isDirectory()) {
          // 递归扫描子目录
          await scanDirectory(itemPath)
        } else if (item.isFile()) {
          // 统计文件类型
          totalFiles++
          const ext = extname(item.name).toLowerCase()
          const fileType = ext || '无扩展名'
          
          fileTypes[fileType] = (fileTypes[fileType] || 0) + 1

          // 检查是否为JS/TS文件，并检查类型安全性
          if (['.ts', '.tsx', '.js', '.jsx'].includes(ext)) {
            totalJsTs++
            
            const isTypeSafe = await isTypeSafeFile(itemPath)
            if (isTypeSafe) {
              totalTypeSafeFiles++
              typeSafeJsTs++
              const typeSafeType = `${ext}(类型安全)`
              typeSafeFiles[typeSafeType] = (typeSafeFiles[typeSafeType] || 0) + 1
            }
          }
        }
      }
    } catch (error: any) {
      // 如果访问某个子目录失败，继续处理其他目录
      console.warn(`无法访问目录 ${currentPath}:`, error.message)
    }
  }

  try {
    // 检查目录是否存在
    await fs.access(directoryPath)
    const stat = await fs.stat(directoryPath)
    
    if (!stat.isDirectory()) {
      throw new Error('指定的路径不是一个目录')
    }
    
    await scanDirectory(directoryPath)
    
    return {
      totalFiles,
      fileTypes,
      typeSafeFiles: {
        total: totalTypeSafeFiles,
        byType: typeSafeFiles,
        percentage: totalFiles > 0 ? Math.round((totalTypeSafeFiles / totalFiles) * 100) : 0
      },
      jstsFiles: {
        total: totalJsTs,
        typeSafe: typeSafeJsTs,
        regular: totalJsTs - typeSafeJsTs,
        typeSafePercentage: totalJsTs > 0 ? Math.round((typeSafeJsTs / totalJsTs) * 100) : 0
      }
    }
  } catch (error: any) {
    if (error.code === 'ENOENT') {
      throw new Error('目录不存在')
    } else if (error.code === 'EACCES') {
      throw new Error('没有权限访问此目录')
    } else {
      throw new Error(error.message || '无法分析目录')
    }
  }
} 